﻿using DevExpress.Mvvm.Native;
using HandyControl.Controls;
using PlaceOrder_Core.Helper;
using PlaceOrder_Core.Services.Instances;
using PlaceOrder_Shared.Models.Common;
using PlaceOrder_Shared.ModelsToLily;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PlaceOrder_Client.Events;
using PlaceOrder_Core.Services.Interfaces;
using PlaceOrder_Core.Models.QuanYi;
using PlaceOrder_Core.PlaceOrderModels;
using PlaceOrder_Client.Views;
using DevExpress.Mvvm;
using Microsoft.Windows.Input;
namespace PlaceOrder_Client.ViewModels
{
    public class RequestChatMessageReviewViewModel:Prism.Mvvm.BindableBase
    {
        #region 依赖属性
        /// <summary>
        /// 多选
        /// </summary>
        private ObservableCollection<string> tradeList;

        /// <summary>
        /// 多选绑定对象
        /// </summary>
        public ObservableCollection<string> TradeList
        {
            get { return tradeList; }
            set { tradeList = value; RaisePropertyChanged(); }
        }

        private string reviewInfoMessage;

        public string ReviewInfoMessage
        {
            get { return reviewInfoMessage; }
            set { reviewInfoMessage = value; RaisePropertyChanged(); }
        }

        private string chatMessage;

        public string ChatMessage
        {
            get { return chatMessage; }
            set { chatMessage = value;RaisePropertyChanged(); }
        }

        private string brokerName;

       

        public string BrokerName
        {
            get { return brokerName; }
            set { brokerName = value; RaisePropertyChanged(); }
        }

        public string? MessageId { get; }

        #endregion

        public Action CloseWindowAction { get; set; }
        public List<UserTrade> TradeModels { get; set; }
        public long? TradeId { get; set; }
        public DelegateCommand ReviewCommand { get; set; }
        public RequestChatMessageReviewViewModel(int brokerId,string? brokerName, string? chatMessage, string? messageId,long? tradeId)
        {
            InitTradeList(brokerId);

          
        
            this.BrokerName = brokerName;
            this.ChatMessage = chatMessage;
            MessageId = messageId;
            TradeId=tradeId;
            ReviewCommand = new DelegateCommand(ReviewToServer);

          
            ChatCheckBoxEventService.CheckComboBoxSelectionChanged2 -= OnCheckComboBoxSelectionChanged;

            ChatCheckBoxEventService.CheckComboBoxSelectionChanged2 += OnCheckComboBoxSelectionChanged;
        }

        private void SelectCurrentBorkerIdTradeList(ObservableCollection<string> tradeList)
        {
            if(TradeList!=null&&tradeList.Count>0)
            {

            }
        }

        private async void OnCheckComboBoxSelectionChanged(object? sender, CheckComboBoxSelectionEventArgs e)
        {
            if (e.AddedItems != null)
            {
                foreach (var item in e.AddedItems)
                {
                    // 检查 ChatWindows 是否已经包含这个 ChatWindowViewModel
                    if (TradeList.Any(vm => vm == item))
                    {
                        //Growl.WarningGlobal(item + "已经存在");
                    }
                    else
                    {
                        // 模拟异步操作，例如数据库查询
                        await Task.Delay(100); // 异步等待，模拟数据库查询或其他异步操作

                      
                    }
                }

                // 处理选中项的逻辑
            }

            if (e.RemovedItems != null)
            {
                foreach (var item in e.RemovedItems)
                {
                    // 查找并移除指定 ChatWindowViewModel
                    TradeList.Remove(item);
                }
            }
        }
        private async void InitTradeList(int brokerId)
        {
            try
            {
                var tradesNew = await Task.Run(() => UserHelper.FindAllXunJiaOrdersAsync());
                var tradeModels = tradesNew.Select(trade => new UserTrade
                {
                    // 根据需要设置 UserTrade 对象的属性
                    // 例如：
                    BrokerID = trade.BrokerId,
                    Status = trade.Status,
                    Price = (decimal)trade.Price,
                    RealPrice = trade.RealPrice,
                    Volume = (int.Parse)(trade.Volume),
                    RealVolume = trade.RealVolume,
                    OnHoldVolume = (int.Parse)(trade.RestVolume),

                    TsCode = trade.Tscode,
                    Time = trade.CreateTime,
                    TradeTime = trade.TradeTime,
                    TradeTime2 = trade.TradeTime2,
                    UpdateTime = trade.UpdateTime,
                    DealType = trade.Direction == "bond_0" ? "买入" : (trade.Direction == "bond_1" ? "卖出" : "未知"), // 根据Direction设置DealType
                    UserTradeID = trade.UserTradeId,
                    ChannelID = trade.ChannelId,
                    DeliveryDate = DateOnly.FromDateTime(trade.DeliveryTime),
                    DeliverySpeed = trade.DeliverySpeed,
                    Target = trade.Target,
                    IsCancelable = trade.Status == 3 || trade.Status == 5 ? false : true,
                    IsChangepriceable = trade.Status == 3 || trade.Status == 5 ? false : true,
                    QiangPingId = !string.IsNullOrEmpty(trade.QiangpingId) ? "1" : null,
                    TradeNum = trade.TradeNum
                    // 其他属性赋值
                }).ToList();
                //筛选出当前通道的所有询价单
                tradeModels = tradeModels.Where(item => item.BrokerID == brokerId).ToList();
                TradeModels = tradeModels;
            
                this.TradeList = TradeModels.Select(o => o.TradeNum).ToList().ToObservableCollection();

          
                if (TradeModels != null && TradeModels.Count > 0)
                {
                    if (TradeId != null && TradeId != 0)
                    {
                        string tradeNum = tradesNew.Where(o => o.UserTradeId == TradeId).FirstOrDefault().TradeNum;
                        if (tradeNum != null)
                        {
                            //                       DevExpress.Mvvm.Messenger.Default.Send(
                            //                       tradeNum,
                            //   "DefaultTradeMessageToken"  // token

                            //);
                           Messenger.Default.Send(tradeNum, "DefaultTradeMessageToken");
                        }
                      

                    }

                }

            }
            catch (Exception ex)
            {
                AppLog.WriteError($"聊天消息提交审核异常,{ex.StackTrace},{ex.Message}");
            }


        }

        public static List<string> SelectedTradeNums = null;
        private async void ReviewToServer()
        {
            if (string.IsNullOrEmpty(ReviewInfoMessage))
            {
                Growl.WarningGlobal("请输入复议内容，不能为空！");
                return;
            }
            var chatWorkOrder = new ChatWorkOrder();
        
            chatWorkOrder.Remarks = this.ReviewInfoMessage;
            chatWorkOrder.MessageId = this.MessageId;
            if(SelectedTradeNums==null||SelectedTradeNums.Count==0)
            {
                Growl.WarningGlobal("必须选中相关询价单！");
                return;
            }
            // 获取 SelectedTradeNums 中的 TradeModels
            var tradeIds = this.TradeModels
                .Where(model => SelectedTradeNums.Contains(model.TradeNum)) // 根据 TradeNum 匹配
                .Select(model => model.UserTradeID.ToString()) // 提取 TradeId
                .ToList(); // 转换为 List<int>
            chatWorkOrder.TradeIds = tradeIds;
            bool result = await UserHelper.ReviewChatWorkOrder(chatWorkOrder);
            if (result)
            {
                Growl.SuccessGlobal($"发送聊天审议消息给审核员成功~");
                AppLog.WriteInfo($"发送审议消息 {ReviewInfoMessage}, 相关TradeIds={string.Join(",", chatWorkOrder.TradeIds.Select(id => id.ToString()))} 给审核员成功~");

            }
            else
            {
                Growl.WarningGlobal($"发送聊天审议消息给审核员失败！");
                AppLog.WriteInfo($"发送审议消息 {ReviewInfoMessage}, 相关TradeIds={string.Join(",", chatWorkOrder.TradeIds.Select(id => id.ToString()))} 给审核员，失败！");
            }

            //Messenger.Default.Send(ReviewInfoMessage, MessageToken.SendReviewMessage);
            CloseWindowAction?.Invoke();
        }

        // 关闭窗口的方法
        private void CloseWindow()
        {
            CloseWindowAction?.Invoke();
        }
    }
}
